import Vue from 'vue'
import VueRouter from 'vue-router'

// 导入组件页面
import login from '@/views/login'
import layout from '@/views/layout'
import home from '@/views/home'
import ask from '@/views/ask'
import mine from '@/views/mine'

import article from '@/views/article'
import edit from '@/views/mine/edit'
import video from '@/views/video'
import store from '@/store'
import search from '@/views/search'
import result from '@/views/search/result'
import chat from '@/views/mine/chat'

Vue.use(VueRouter)
const routes = [
  { path: '/', redirect: '/layout/home' },
  { name: 'login', path: '/login', component: login },
  { name: 'search', path: '/search', component: search },
  { name: 'chat', path: '/mine/chat', component: chat },
  {
    name: 'result',
    path: '/search/result',
    component: result,
    meta: { needKeep: true }
  },
  { name: 'article', path: '/article', component: article },
  {
    name: 'edit',
    path: '/mine/edit',
    component: edit,
    meta: {
      needLogin: true
    }
  },
  {
    name: 'layout',
    path: '/layout',
    component: layout,
    children: [
      { name: 'ask', path: 'ask', component: ask },
      { name: 'home', path: 'home', component: home, meta: { needKeep: true } },
      { name: 'video', path: 'video', component: video },
      {
        name: 'mine',
        path: 'mine',
        component: mine,
        meta: {
          needLogin: true
        }
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 前置钩子
router.beforeEach((to, from, next) => {
  // 判断是否需要登录
  if (to.meta.needLogin) {
    // 判断是否有token
    if (store.state.tokenObj.token) {
      // 有token直接通过
      next()
    } else {
      // 没有token的要跳转到登录页面
      Vue.prototype.$toast.fail('请先登录')
      next({
        name: 'login',
        // 携带参数
        query: {
          // 去之前想去的页面没有去成，然后打回到登录页
          back: to.path
        }
      })
    }
  } else {
    // 不需要登录的页面直接跳转
    next()
  }
})

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) {
    return originalPush.call(this, location, onResolve, onReject)
  }
  return originalPush.call(this, location).catch((err) => err)
}

export default router
